package cn.zhaoyuening.chat_client.client;

import cn.zhaoyuening.chat_client.handler.ChatClientHandler;
import cn.zhaoyuening.chat_client.utils.ClientConstant;
import cn.zhaoyuening.chat_common.msg.ChatMsg;
import cn.zhaoyuening.chat_common.utils.MarshallingCodeCFactory;
import cn.zhaoyuening.zamh.handler.MsgHandler;
import cn.zhaoyuening.zamh.manager.MsgManager;
import cn.zhaoyuening.zamh.msg.Msg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Date;

/**
 * Created by Buynow on 2017/6/14.
 */
public class ChatClient implements Runnable {
    private String host;
    private int port;
    private Channel channel;
    private MsgManager msgManager;


    public ChatClient(String host, int port,MsgManager msgManager) {
        this.host = host;
        this.port = port;
        this.msgManager = msgManager;
        msgManager.addHandler(new MsgHandler(ClientConstant.SEND_CHAT_MSG) {
            @Override
            public void handle(Msg msg) {
                if (msg.getInfo() instanceof ChatMsg) {
                    sendChatMsg((ChatMsg) msg.getInfo());
                }
            }
        });
    }

    public void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        ch.pipeline().addLast(new ChatClientHandler(msgManager));
                    }
                });
        try {
            ChannelFuture future = bootstrap.connect(host, port).sync();
            this.channel = future.channel();
            System.out.println("服务器连接成功 ");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }
    }

    public void sendChatMsg(ChatMsg chatMsg) {
        if (channel == null || !channel.isWritable()){
            System.out.println("服务器连接失败 尝试重连");
            run();
            return;
        }
        channel.writeAndFlush(chatMsg);
    }


}
